//
//  FavoritesDatabase.m
//  SmSh iphone
//
//  Created by SmSh on 13-5-28.
//  Copyright (c) 2013年 SmartShanghai. All rights reserved.
//

#import "CardDatabase.h"
#import "PathUtilities.h"
#import "FMDatabaseAdditions.h"

static CardDatabase *cardDatabase = nil;

@implementation CardDatabase


// 目前只在主线程中使用,所以无需考虑多线程情况了
+ (CardDatabase *)sharedInstance{
    if (!cardDatabase) {
        cardDatabase = [[CardDatabase alloc] init];
    }
    return cardDatabase;
}

- (id)init{
	if (self = [super init]) {
		db = [FMDatabase databaseWithPath:[PathUtilities documentFilePathWithFileName:CARD_DB]];
		if (![db open]) {
			NSLog(@"Could not open db.");
			return nil;
		}
		
		[db setShouldCacheStatements:YES];
		
		[db executeUpdate:@"create table  if not exists card (uid  INTEGER PRIMARY KEY ASC, cardId integer, cardStatus integer, cardImage text,cardDescribe text)"];
		
		if ([db hadError]) {
			NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
			return nil;
		}
	}
    
	return self;
}


- (BOOL)updateCardStatus:(NSInteger)cardId WithStatus:(NSInteger)cardStatus {
	NSString *sql = @"update card set cardStatus = ? where cardId = ?";
	return [db executeUpdate:sql,[NSNumber numberWithInt:cardStatus],[NSNumber numberWithInt:cardId]];
}

//add
- (BOOL)addCard:(CardModel *)obj {
	NSString *sql = @"insert into card(cardId, cardStatus, cardImage, cardDescribe) values(?,?,?,?)";
	BOOL result = [db executeUpdate:sql,
				   [NSNumber numberWithInteger:obj.cardId],
				   [NSNumber numberWithInteger:obj.cardStatus],
				   obj.cardImage,
                   obj.cardDescribe];
	return result;
}


- (NSArray *)searchAllCards {
    __autoreleasing NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:0];
	NSString *sql = [NSString stringWithFormat:@"SELECT * FROM card"];
	FMResultSet *resultSet = [db executeQuery:sql];
	while ([resultSet next]) {
        CardModel *obj = [[CardModel alloc] init];
		obj.cardId = [resultSet intForColumn:@"cardId"];
        obj.cardStatus = [resultSet intForColumn:@"cardStatus"];
		obj.cardImage = [resultSet stringForColumn:@"cardImage"];
		obj.cardDescribe = [resultSet stringForColumn:@"cardDescribe"];
		
		[resultArray addObject:obj];
	}
    NSLog(@"searchByArearesultArray=%@",resultArray);
	return resultArray;
}

@end
